package com.qfedu.zf.user.listener;

import cn.hutool.core.util.RandomUtil;
import com.qfedu.zf.common.config.RabbitKeyConfig;
import com.qfedu.zf.common.config.RedisKeyConfig;
import com.qfedu.zf.common.param.MqMsg;
import com.qfedu.zf.core.sms.AliSmsUtil;
import com.qfedu.zf.user.entity.SmsLog;
import com.qfedu.zf.user.mapper.SmsLogMapper;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.concurrent.TimeUnit;

@Component
public class SmsRabbitListener {


    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private SmsLogMapper smsLogMapper;
    /**
     * 队列的消费者
     *
     *  * 发送注册短信业务
     *      * 1.生成随机证码
     *      *
     *      * 2.发送阿里云短信
     *      *
     *      * 3.存入redis中验证码
     *      *
     *      * 4.手机号验证码记录日志表
     */
    @RabbitListener(queues = RabbitKeyConfig.Q_SENDSMS)
    public void smsListener(MqMsg msg){

        System.out.println("消费者得到消息  msg = " + msg);

        // 1.生成随机证码
        // RandomUti(int min, int max)限定 最大值最小值  生成4位随机数
        // String code = RandomUtil.randomInt(1000,9999)+"";

        String code = 8888+"";

        //  2.发送阿里云短信
        String phone = (String) msg.getMsg();
        System.out.println("phone = " + phone + "---验证码 = "+code);
        boolean result = AliSmsUtil.sendCode(phone, code);

        if (true){ // 只有发送验证码成功才存储验证码  true模仿发送成功

            switch (msg.getType()){
                //1.注册验证码
                case  1:
//                    3.存入redis中验证码
                    stringRedisTemplate.opsForValue().set(RedisKeyConfig.SMS_RCODE+phone,code,RedisKeyConfig.SMS_RCODE_TIME, TimeUnit.SECONDS);

                    // 4.手机号验证码记录日志表
                    smsLogMapper.insert(new SmsLog(phone,"注册验证码",phone+"注册-验证码："+code,new Date()));
                    break;

                // 2.登录验证码
                case  2:

                    break;

                //3.密码找回验证码
                case  3:

                    break;
                default:
                    System.out.println("其他消息处理");
                    break;
            }

        }

    }


}
